# coding: utf-8
# Author: legend
# @Time： 2020/8/27 下午10:05
import asyncio

import aioredis

import settings

pool = aioredis.create_redis_pool(address=f'{settings.REDIS_IP}:settings.REDIS_PORT',
                                  password=settings.REDIS_PASSWORD,
                                  db=0, minsize=3, maxsize=10)


class Redis:
    _redis = None

    async def get_redis_pool(self, *args, **kwargs):
        if not self._redis:
            self._redis = await aioredis.create_redis_pool(*args, **kwargs)
        return self._redis

    async def close(self):
        if self._redis:
            self._redis.close()
            await self._redis.wait_closed()

    def __enter__(self) -> None:
        raise TypeError("Use async with instead")

    async def __aenter__(self):
        await self.get_redis_pool(address=(settings.REDIS_IP, settings.REDIS_PORT),
                                  password=settings.REDIS_PASSWORD,
                                  db=0)
        return self._redis

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.close()


def check(conn, key, value):
    """
    对比value与服务器上的value是否一致

    :param conn:
    :param key:
    :param value:
    :return: boolean
    """
    try:
        redis_value = str(conn.get(key), "utf-8")
        return True if redis_value == value else False
    except TypeError:
        return False


class RedisQueue(object):
    def __init__(self, connect, key):
        self._conn = connect
        self._key = key

    def size(self):
        return self._conn.llen(self._key)

    def put(self, item):
        self._conn.rpush(self._key, item)

    def get_wait(self, timeout=None):
        item = self._conn.blpop(self._key, timeout=timeout)
        return item

    def get_nowait(self):
        item = self._conn.lpop(self._key)
        return item

    def reset(self):
        self._conn.delete(self._key)


async def xx():
    async with Redis() as redis:
        result = await redis.get('app_cache_2000')
        print(result.decode('utf-8', 'ignore'))


def test():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.gather(*[xx(), ]))


if __name__ == '__main__':
    test()
